package com.liusand.client.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.liusand.common.thread.UsersThreadLocal;
import com.liusand.model.pojo.Users;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义一个拦截器，实现 HandlerInterceptor
 */
public class UsersInterceptor implements HandlerInterceptor {

    // 前置拦截
    // 主要做的事：获取从gateway传递过来的用户信息
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头上的用户信息
        String token = request.getHeader("token");
        boolean verify = JWTUtil.verify(token, "ABCDEFG".getBytes());
        if(!verify){
            return false;
        }
        JWT jwt = JWTUtil.parseToken(token);
        Integer id = Integer.parseInt((String) jwt.getPayload("id"));
        String openId = (String) jwt.getPayload("openId");

        if (StringUtils.isEmpty(openId)) {
            return false;
        }

        // 2. 将id参数放到ThreadLocal里面
        Users users = new Users();
        users.setId(id);
        users.setOpenId(openId);
        UsersThreadLocal.set(users);
        return true;
    }

    // 完成时拦截
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        // 固定操作，删除不需要的ThreadLocal数据
        UsersThreadLocal.remove();
    }
}
